package com.zcsy.manage.web.base;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CellBuilding;
import com.zcsy.manage.model.base.CellHouse;
import com.zcsy.manage.model.base.CellRegion;
import com.zcsy.manage.model.base.CellUnit;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.persistence.weixin.StringUtil;
import com.zcsy.manage.service.base.ICellBuildingService;
import com.zcsy.manage.service.base.ICellHouseService;
import com.zcsy.manage.service.base.ICellRegionService;
import com.zcsy.manage.service.base.ICellUnitService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;

/**
 * 
 * @Title: CellUnitController.java
 * @Package： com.zcsy.manage.web.base 
 * @Description: 单元信息控制器
 * @author zhangsh zsh3384027@gmail.com
 * @Copyright: 2016 武汉恒数利通技术有限公司 All rights reserved.
 * @date 2016年4月9日
 * @version 1.0
 * @see JDK1.8.0_45
 * @since
 */
@Controller
@RequestMapping(value= "/cellUnit")
public class CellUnitController {
	
	@Autowired
	private ICellUnitService cellUnitService;
	
	@Autowired
	private ICellRegionService cellRegionService;
	
	@Autowired
	private ICellBuildingService cellBuildingService;
	
	@Autowired
	private ICellHouseService cellHouseService;

	@Autowired
	private IDictService dictService;
	
	/**
	 * 
	 * @Description 根据关键字查询 单元列表
	 * @param model
	 * @param pNo
	 * @param cellid
	 * @param regionid
	 * @param buildingId
	 * @param unitName
	 * @param req
	 * @return 
	 * @author zhangsh zsh3384027@gmail.com
	 * @date 2016年4月9日
	 * @see
	 */
	@RequestMapping(value = "/cellUnitList", method=RequestMethod.GET)
	public String cellUnitList(Model model, Integer pNo, Integer pSize, 
			String regionId,String buildingId,String unitName, HttpServletRequest req) {
		if(pNo == null){
    		pNo = Constants.PAGE_NO;
    	}

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
        CellUnit cellUnit = new CellUnit();
        
        //获取当前小区信息
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();
        cellUnit.setCellId(cellId);
        
        //根据cellId查询当前小区区域
        List<CellRegion> cellRegions = cellRegionService.getCellRegionByCellId(cellId);
        
        if(StringUtils.isNotEmpty(regionId)){
        	cellUnit.setRegionId(regionId);
        }
        if(StringUtils.isNotEmpty(buildingId)){
        	cellUnit.setBuildingId(buildingId);
        }
        if(StringUtils.isNotEmpty(unitName)){
        	cellUnit.setName(unitName);
        }
        
        //此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);
        
        List<CellUnit> cellUnitlist = cellUnitService.selectByKeyword(cellUnit);
        PageInfo<CellUnit> unit = new PageInfo<CellUnit>(cellUnitlist);
        
        model.addAttribute("cellUnits",unit);
        model.addAttribute("cellRegions", cellRegions);
        model.addAttribute("regionid",regionId);
        model.addAttribute("buildingid",buildingId);
        model.addAttribute("unitName",unitName);
        model.addAttribute("currentPage",pNo);
		model.addAttribute("pSize", pSize);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

        return "base/cellunit/cellunitList";
	}
	
	/**
	 * 
	 * @Description 根据cellid获取region信息
	 * @param cellid
	 * @return 
	 * @author zhangsh zsh3384027@gmail.com
	 * @date 2016年4月11日
	 * @see
	 */
	@RequestMapping(value = "/getRegionByCellId")
	@ResponseBody
	public RequestJson getRegionByCellId(String cellid, HttpServletRequest req){
		RequestJson result = new RequestJson();
		try{
			if (StringUtils.isNotEmpty(cellid)) {
				List<CellRegion> cellRegion = new ArrayList<CellRegion>();
				cellRegion = cellRegionService.getCellRegionByCellId(cellid);
				result.setObj(cellRegion);
				result.setSuccess(true);
			}else{
				result.setSuccess(false);
			}
		}catch(Exception e){
			result.setSuccess(false);
		}
		return result;
	}
	
	/**
	 * 
	 * @Description 根据regionid获取楼栋信息
	 * @param cellid
	 * @return 
	 * @author zhangsh zsh3384027@gmail.com
	 * @date 2016年4月11日
	 * @see
	 */
	@RequestMapping(value = "/getBuildingByRegionId")
	@ResponseBody
	public RequestJson getBuildingByRegionId(String regionid, HttpServletRequest req){
		RequestJson result = new RequestJson();
		try{
			if (StringUtils.isNotEmpty(regionid)) {
				List<CellBuilding> cellBuilding = new ArrayList<CellBuilding>();
				cellBuilding = cellBuildingService.getCellBuildingByRegionId(regionid);
				result.setObj(cellBuilding);
				result.setSuccess(true);
			}else{
				result.setSuccess(false);
			}
		}catch(Exception e){
			result.setSuccess(false);
		}
		return result;
	}
	
	/**
	 * 
	 * @Description 新增或编辑
	 * @param model
	 * @param id 主键id，id=0新增，id!=0编辑
	 * @return 
	 * @author zhangsh zsh3384027@gmail.com
	 * @date 2016年4月9日
	 * @see
	 */
	@RequestMapping(value= "/editcellUnit")
	public String editCellUnit(Model model, String id, HttpServletRequest req){
		try{
    		if(String.valueOf(Constants.STATE_DISABLED).equals(id)){
    		    
    			model.addAttribute("type",Constants.SAVE_TYPE);
    			
    		} else{
    			CellUnit cellUnit = cellUnitService.selectByPrimaryKey(id);
    			
    			if(cellUnit != null){
    				model.addAttribute("type",Constants.EDIT_TYPE);
    				model.addAttribute("cellUnit",cellUnit);
    			}
    		}
    		User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            String cellid = user.getCurrentCell().getId();
            List<CellRegion> cellRegions = cellRegionService.getCellRegionByCellId(cellid);
            
            model.addAttribute("cellRegions", cellRegions);
    	} 
    	catch(Exception e){
    	}
    	return "base/cellunit/CellunitEdit";
	}
	/**
	 * 
	 * @Description 保存更新小区单元
	 * @author zhangsh zsh3384027@gmail.com
	 * @date 2016年4月12日
	 * @see
	 */
	@RequestMapping(value = "/saveOrUpdateCellunit", method = RequestMethod.POST)
	@ResponseBody
	public RequestJson saveOrUpdate(Model model, String id,String name, 
			String regionid,String buildingid,
			String buildingName,String cellName,String regionName,Integer sort,
			String memo,HttpServletRequest req) {
		RequestJson result = new RequestJson();
		CellUnit cellUnit = new CellUnit();
		User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellid = user.getCurrentCell().getId();
		cellUnit.setName(name);
		cellUnit.setRegionId(regionid);
		cellUnit.setBuildingId(buildingid);
		cellUnit.setRegionName(regionName);
		cellUnit.setBuildingName(buildingName);
		cellUnit.setMemo(memo);
		cellUnit.setSort(sort);
		cellUnit.setUserAccount(user.getLoginname());
		try {
		    boolean isUpdate = (id != null && !"0".equals(id));
		    if(StringUtil.isEmptyString(buildingid)) {
		        buildingid = cellUnitService.selectByPrimaryKey(id).getBuildingId();
            }
            boolean nameExists = cellUnitService.isNameExists(isUpdate ? id : null, buildingid, name);
            if(nameExists) {
                result.setSuccess(false);
                result.setMsg("单元名称已存在");
            } else {
                
                if (isUpdate) {
                    cellUnit.setId(id);
                    cellUnit.setUpdateTime(new Date());
                    cellUnitService.update(cellUnit);
                    LogUtils.insertLog("用户编辑小区单元信息", user.getId(), req);
                } else {
                    cellUnit.setId(UniqueNumberUtils.get18UniqueNumber());
                    cellUnit.setSendTime(new Date());
                    cellUnit.setCellId(cellid);
                    cellUnitService.insert(cellUnit);
                    LogUtils.insertLog("用户新增小区单元信息", user.getId(), req);
                }
                result.setSuccess(true);
            }
		    
		} catch (Exception e) {
		    result.setSuccess(false);
			result.setMsg("操作失败！");
		}
		return result;
	}
	
	/**
	 * 
	 * @Description 单元信息详情
	 * @author zhangsh zsh3384027@gmail.com
	 * @date 2016年4月12日
	 * @see
	 */
	@RequestMapping(value = "/cellUnitdetail", method = RequestMethod.GET)
	public String cellUnitDetail(Model model, String id, HttpServletRequest req){
		try {
			CellUnit cellUnitInfo = cellUnitService.selectByPrimaryKey(id);
			if(cellUnitInfo != null){
				model.addAttribute("cellUnitInfo", cellUnitInfo);
            }
        } catch (Exception e) {
        }
		
		return "base/cellunit/cellunitDetail";
	}

	/**
	 * @Description 批量删除  单元信息
	 * @author zhangsh zsh3384027@gmail.com
	 * @date 2016年4月9日
	 * @see
	 */
	@RequestMapping(value = "/deleteCellunit", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deleteByPrimaryKey(String ids, HttpServletRequest req){
    	RequestJson result = new RequestJson();
    	User user  = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
    	try{
    		String keys[] = ids.split("\\,");
    		for (int i = 0; i < keys.length; i++ ) {
    			List<CellHouse> cellHouse = cellHouseService.getCellHouseByUnitId(keys[i]);
    			CellUnit cellUnit = cellUnitService.selectByPrimaryKey(keys[i]);
    			if(CollectionUtils.isEmpty(cellHouse)){
    				cellUnitService.deleteByPrimaryKey(keys[i]);
    				result.setSuccess(true);
    				LogUtils.insertLog("用户删除单元信息", user.getId(), req);
    			}else{
    				result.setMsg(cellUnit.getName()+"单元已被引用，不能删除！");
    				result.setSuccess(false);
    			}
    		}
    	} catch (NumberFormatException e) {
    		result.setSuccess(false);
    		result.setMsg("操作失败");
    	}
    	return result;
    }

	/**
	 * @Description 根据排序实现置顶功能，即修改当前排序为最大排序值加1，并且更新修改时间<br>
	 * @param id 商品id
	 * @param req 用户请求
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年6月3日
	 * @see 
	 */
	@RequestMapping(value="updateSort" , method = RequestMethod.GET)
	@ResponseBody
    public RequestJson updateSort( String id,HttpServletRequest req){
        RequestJson result = new RequestJson();
        User user  = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        try {
        	CellUnit cellUnit = cellUnitService.selectByPrimaryKey(id);
        	if(cellUnit != null){
        		cellUnit.setUpdateTime(DateUtils.getDate());
        		cellUnitService.updateSort(cellUnit);
        		LogUtils.insertLog("用户置顶小区单元", user.getId(), req);
        	}
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setSuccess(false);
        }
       
        return result;
    }
}
